package cn.ztuo.bitrade.service;

import cn.ztuo.bitrade.constant.CommonStatus;
import cn.ztuo.bitrade.dao.CoinDao;
import cn.ztuo.bitrade.dao.EarningsTreasureDao;
import cn.ztuo.bitrade.entity.Coin;
import cn.ztuo.bitrade.entity.EarningsTreasure;
import cn.ztuo.bitrade.entity.QEarningsTreasure;
import cn.ztuo.bitrade.service.Base.BaseService;
import cn.ztuo.bitrade.util.MessageResult;
import cn.ztuo.bitrade.util.PredicateUtils;
import cn.ztuo.bitrade.util.RedisUtil;
import cn.ztuo.bitrade.vo.EarningsTreasureVO;
import com.alibaba.fastjson.JSONObject;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

import static cn.ztuo.bitrade.util.MessageResult.error;
import static cn.ztuo.bitrade.util.MessageResult.success;

@Slf4j
@Service
public class EarningsTreasureService extends BaseService<EarningsTreasure> {

    @Autowired
    private EarningsTreasureDao earningsTreasureDao;

    @Autowired
    private CoinDao coinDao;

    @Autowired
    private RedisUtil redisUtil;

    public EarningsTreasure getById(Long id) {
        return earningsTreasureDao.findById(id);
    }

    public Page<EarningsTreasure> getByPage(EarningsTreasureVO earningsTreasureVO) throws Exception {
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();

        // 查询条件
        if (StringUtils.isNotEmpty(earningsTreasureVO.getTitle())) {
            booleanExpressions.add(QEarningsTreasure.earningsTreasure.title.like("%" + earningsTreasureVO.getTitle() + "%"));
        }
        if (StringUtils.isNotEmpty(earningsTreasureVO.getCoin())) {
            booleanExpressions.add(QEarningsTreasure.earningsTreasure.coin.name.like("%" + earningsTreasureVO.getCoin() + "%"));
        }
        if (earningsTreasureVO.getStartTime() != null) {
            booleanExpressions.add(QEarningsTreasure.earningsTreasure.createTime.goe(earningsTreasureVO.getStartTime()));
        }
        if (earningsTreasureVO.getEndTime() != null) {
            booleanExpressions.add(QEarningsTreasure.earningsTreasure.createTime.loe(earningsTreasureVO.getEndTime()));
        }
        if (earningsTreasureVO.getStatus() != null) {
            booleanExpressions.add(QEarningsTreasure.earningsTreasure.status.eq(earningsTreasureVO.getStatus()));
        }
        Predicate predicate = PredicateUtils.getPredicate(booleanExpressions);
        // 排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = new PageRequest(earningsTreasureVO.getPageNum() - 1, earningsTreasureVO.getPageSize(), sort);
        return earningsTreasureDao.findAll(predicate, pageable);

    }

    @Transactional
    public MessageResult saveEarningsTreasure(EarningsTreasure earningsTreasure) {
        log.info("保存/修改收益宝" + JSONObject.toJSONString(earningsTreasure));
        if (earningsTreasure.getId() == null) {
            Coin coin = earningsTreasure.getCoin();
            if (coin == null) {
                return error(500, "发售币种不存在");
            } else if (coin.getStatus().equals(CommonStatus.ILLEGAL)) {
                return error(400, "发售币种被禁用");
            }
        }
        // 结束时间从 所填写的结束时间的第二天的00.00.00算
        earningsTreasure.setEndTime(earningsTreasure.getEndTime().plusDays(1));

        EarningsTreasure result = earningsTreasureDao.save(earningsTreasure);
        Long id = result.getId();

        LocalDateTime now = LocalDateTime.now();
        // 开始时间与当前时间时间差
        long startSeconds = ChronoUnit.SECONDS.between(now, earningsTreasure.getStartTime());
        // 当前时间与结束时间时间差
        long endSeconds = ChronoUnit.SECONDS.between(now, earningsTreasure.getEndTime());

        // 如果未到开始时间，将id存进redis中，过期时间为当前时间和开始时间的时间差（单位为秒），状态为未开始
        // 如果已到开始时间，将id存进redis中，过期时间为结束时间和当前时间的时间差（单位为秒），状态为出售中
        redisUtil.set("earningsTreasure:end:" + id, id, endSeconds);
        if (startSeconds > 0) {
            redisUtil.set("earningsTreasure:start:" + id, id, startSeconds);
            earningsTreasure.setStatus(2);
        } else {
            earningsTreasure.setStatus(1);
        }
        earningsTreasureDao.save(result);
        if (result.getId() > 0) {
            return success("操作成功");
        } else {
            return error("操作失败");
        }
    }

    public List<EarningsTreasure> findAllByStatus() {
        return earningsTreasureDao.findAllByStatus();

    }

    public EarningsTreasure inster(EarningsTreasure earningsTreasure) {
        return earningsTreasureDao.save(earningsTreasure);
    }

}
